import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/services.dart';

const platform = MethodChannel('app/invokeMethod');

class MethodBridge {
// 静态变量持有Singleton的实例
  static MethodBridge? _instance;

  // 私有构造函数，确保外部不能通过new Singleton()来创建实例
  MethodBridge._privateConstructor() {
    // 初始化代码（如果需要）
  }

  // 静态方法，用于获取Singleton的实例
  static MethodBridge getInstance() {
    // 如果_instance为空，则创建一个新的实例
    if (_instance == null) {
      _instance = MethodBridge._privateConstructor();
    }
    // 返回Singleton的实例
    return _instance!;
  }

  // 调用原生方法展示ViewController
  Future<void> showLiveVc(Map<String, dynamic> model) async {
    try {
      await platform.invokeMethod('showLiveVc', model);
    } on PlatformException catch (e) {
      // print("Failed to invoke method: " + e.message);
    }
  }

  Future<void> print(String msg) async {
    try {
      await platform.invokeMethod('print', msg);
    } on PlatformException catch (e) {
      // print("Failed to invoke method: " + e.message);
    }
  }

  Future<Map<String, dynamic>> request(String url, Map<String, dynamic> parameters) async {
    try {
      final responseBody = await platform.invokeMethod('request', {"url": url, "parameters": parameters});
      Map<String, dynamic> dataMap = jsonDecode(responseBody);
      return dataMap;
    } on PlatformException catch (e) {
      throw Exception('Error fetching data: $e');
    }
  }




  void showTip(String msg) {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );
  }


  Future<void> exit() async {
    try {
      await platform.invokeMethod('exit');
    } on PlatformException catch (e) {
      // print("Failed to invoke method: " + e.message);
    }
  }
}